// SubMenu.cpp: implementation of the SubMenu class.
//
//////////////////////////////////////////////////////////////////////

#include "SubMenu.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

SubMenu::SubMenu(float x, float y, int col, float icon_w, float icon_h)
{
this->start_x = x;
this->start_y = y;

this->cols = col;

this->icon_w = icon_w;
this->icon_h = icon_h;

this->selected = false;
this->show     = false;

this->menuEntries = new ulLinkedList();
this->numMenuEntries = 0;

old_sel = -1;
curr_sel = -1;
}

SubMenu::~SubMenu()
{

}

int SubMenu::passive(int button, int state, int x, int y)
{
int over = 0;

if(show)
	{
	for(int i = 0; i < numMenuEntries; i++)
		{
		IconButton *ib = (IconButton*)menuEntries->getNodeData(i);
		over += ib->mouse(button,state,x,y);
		}
	}
if(over > 0) this->focused = true;
else this->focused = false;
return focused;
}

int SubMenu::mouse(int button, int state, int x, int y)
{
int over = 0;

if(show)
	{
	for(int i = 0; i < numMenuEntries; i++)
		{
		IconButton *ib = (IconButton*)menuEntries->getNodeData(i);
		over += ib->mouse(button,state,x,y);
		if(ib->selected()) 
			{
			if( (old_sel != i) && (old_sel != -1) )
				{
				IconButton *ib_old = (IconButton*)menuEntries->getNodeData(old_sel);
				ib_old->change();
				}
			old_sel = i;
			}
		}
	if( button == GLUT_LEFT_BUTTON ) this->hide();
	}


if(over > 0) this->focused = true;
else this->focused = false;
return focused;
}

bool SubMenu::isFocused()
{
return focused;
}

void SubMenu::display()
{
if(show)
	{
	for(int i = 0; i < numMenuEntries; i++)
		{
		IconButton *ib = (IconButton*)menuEntries->getNodeData(i);
		ib->display();
		}
	}
}

void SubMenu::reveal()
{
this->show = true;
}

void SubMenu::hide()
{
this->show = false;
}


bool SubMenu::isVisible()
{
return show;
}

int SubMenu::getSelectedEntry()
{
int sel_entry = -1;

for(int i = 0; i < numMenuEntries; i++)
	{
	IconButton *ib = (IconButton*)menuEntries->getNodeData(i);
	if(ib->selected()) sel_entry = i;
	}
return sel_entry;
}

void SubMenu::add(IconButton *ib)
{
ib->set(start_x + (float)(numMenuEntries%cols)*icon_w, start_y - (float)(numMenuEntries/cols)*icon_h,icon_w,icon_h);
//printf("%f %f %f %f\n",start_x + (float)(numMenuEntries%cols)*icon_w, start_y - (float)(numMenuEntries/cols)*icon_h,icon_w,icon_h);
this->menuEntries->appendNode(ib);
if(numMenuEntries == 0) ib->change(); // one selected by default
this->numMenuEntries++;
}

void SubMenu::bindTextures()
{
for(int i = 0; i < numMenuEntries; i++)
	{
	IconButton *ib = (IconButton*)menuEntries->getNodeData(i);
	ib->bindTexture();
	}
}

bool SubMenu::isSelected()
{
return selected;
}
